A smooth intro to map visualization in R

https://medium.com/@marcomichelangeli/a-smooth-intro-to-map-visualization-in-r-28a3887bd84c

Lately I found myself working a bit with geo data, learning many things of a niche, but very interesting field! After all this work therefore I have decided to share what I have learned by writing a small series of posts (I hope to have time for it!) aimed to introduce newby to this field of work. I presuppose only that you know a bit of R and its main packages. B ut lets get started! In this first post I would like to smoothly introduce the R packages that are mostly used with geodata and show how easy is to plot points on map!

We will use the following packages:

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggmap)
## Loading required package: ggplot2
library(jsonlite)

####ggmap() and qmap() First package to introduce is ggmap. It is simply a wrapper for mainly the google map API (it also support Stamen and OpenStreet among others).The main functions of ggmap are get_map() and ggmap(). Give them a location coordinates and the map is yours!

# First get Milan coordinates
Milan<-c(lon=9.191383, lat=45.464211)
#Extract the map from Google map at a specific zoom (this is up to you!)
mapMilan <- get_map(location=Milan, zoom=10)
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=45.464211,9.191383&zoom=10&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
#Visualize the map
ggmap(mapMilan)

This is awesome and super easy! And it will get easier: ggmap has another function for doing the same operation in less coding, it is called qmap() and works as follows:

mapMilan<-qmap("Milan", zoom = 10)
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=Milan&zoom=10&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=Milan&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead
mapMilan


No need for coordinates and we get a one step process (get map + visualization). As we do with ggplot() and plot() we need to decide if we want a more complete function (ggmap()), with more freedom for visualizing multiple layers of data or if we want a quick and fast function that just spits out a map (qmap()). ggmap customization

The customization of ggmap is almost endless and we will see more in next articles. Here I will point you out just that we can have different looking maps using different sources or different google map types. As an example let us look at the same map above using a satellite map type

#Get the map
mapMilanSat <- get_map(location=Milan, zoom=10, maptype = "satellite")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=45.464211,9.191383&zoom=10&size=640x640&scale=2&maptype=satellite&language=en-EN&sensor=false
#Visualize the map
ggmap(mapMilanSat)


Or a map from Stamen instead of Google:

#Get the map
mapMilanStamen <- get_map(location=Milan, zoom=10, source= "stamen", maptype = "toner-2011")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=45.464211,9.191383&zoom=10&size=640x640&scale=2&maptype=terrain&sensor=false
## Map from URL : http://tile.stamen.com/toner-2011/10/536/365.png
## Map from URL : http://tile.stamen.com/toner-2011/10/537/365.png
## Map from URL : http://tile.stamen.com/toner-2011/10/538/365.png
## Map from URL : http://tile.stamen.com/toner-2011/10/539/365.png
## Map from URL : http://tile.stamen.com/toner-2011/10/536/366.png
## Map from URL : http://tile.stamen.com/toner-2011/10/537/366.png
## Map from URL : http://tile.stamen.com/toner-2011/10/538/366.png
## Map from URL : http://tile.stamen.com/toner-2011/10/539/366.png
## Map from URL : http://tile.stamen.com/toner-2011/10/536/367.png
## Map from URL : http://tile.stamen.com/toner-2011/10/537/367.png
## Map from URL : http://tile.stamen.com/toner-2011/10/538/367.png
## Map from URL : http://tile.stamen.com/toner-2011/10/539/367.png
#Visualize the map
ggmap(mapMilanStamen)


Nice right? If you want to know more about possible sources and map types or other ggmap customization just type ?ggmap on your console! data layer

But wait…what is the usefulness of a map without data on it? So yes, we need to do a step forward and add some point positions to our map layer. First let’s generate some data. We will get the coordinates of 20 groceries in Milan from google places API and add them to a data frame. If you do not want to bother using this data, just grab a dataframe with coordinates position and skip ahead!

#We will use jsonlite library to connect to Google API
library(jsonlite)
#Store the Google Place API (you need to sign up on their website)
key<-"AIzaSyCuwJehFmJwsh7hf1Wf_6Ezb9oUuK7PuFA"

#Compose the first part of the API call
plcurl<-"https://maps.googleapis.com/maps/api/place/textsearch/json?location="

#Store the coordinates around which Google will look for groceries 
location.lat <-"45.464211"
location.lng <-"9.191383"
location<-paste(location.lat,",",location.lng)

#Tell Goggle what is the radius (Km) within which it has to look
radius<-"50000"

#Tell Google what to look for
query<-"groceries"

#Structure the request and send it!
strurl<-as.character(paste(plcurl,location, "&query=", query,"&radius=",radius,"&key=",key, sep=""))

rd<-fromJSON(URLencode(strurl))
addresses<-rd$results$formatted_address

#Google return a JSOn so we need to put it into a dataframe
coords <- data.frame(Longitude = as.numeric(as.character(rd$results$geometry$location$lng)),Latitude = as.numeric(as.character(rd$results$geometry$location$lat)),Address=as.character(rd$results$formatted_address), stringsAsFactors = FALSE)

Our dataframe looks like this:

head(coords)
##   Longitude Latitude
## 1  9.193791 45.46999
## 2  9.035059 45.83605
## 3  9.014978 45.84638
## 4  9.226446 45.51779
## 5  9.074593 45.81235
## 6  9.204258 45.47608
##                                                   Address
## 1              Via Borgospesso, 1, 20121 Milano MI, Italy
## 2      Via Alessandro Volta 22, 6830 Chiasso, Switzerland
## 3 Viale Serfontana 16, 6834 Morbio Inferiore, Switzerland
## 4                Viale Monza, 274, 20128 Milano MI, Italy
## 5      Via Recchi, Ang Via Rosselli, 22100 Como CO, Italy
## 6        Via Panfilo Castaldi, 32, 20124 Milano MI, Italy

This coordinates can be easily superimposed to our map layer using (as in ggplot()) geom_point():

mapMilan +
  geom_point(data=coords, aes(x=Longitude,y=Latitude), color="red", size=3,alpha=0.5)
## Warning: Removed 17 rows containing missing values (geom_point).


How easy was that?? And this is just the beginning, ggmap() opens the door to many possibilities for using geo data in R. In the next posts I will be writing more about what geo data are and how to handle and visualize them in a more elegant and beautiful way.